﻿using System.Globalization;
using AutoMapper;
using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Pages.SMD.Helper;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Workflow.DwzCode;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.Helper;
using System.Web.UI.HtmlControls;
using H2.NET.TaskRob;
using NPOI.SS.Formula.Functions;

namespace H2.NET.Web.Pages.SMD
{
    public partial class ChangeContract : BasePage
    {
        #region 全局变量
        //日志
        public IList<t_StoreDataChangeLog> Logs = new List<t_StoreDataChangeLog>();
        public string step = "";
        public List<t_smd_ContractDevice> ContractDevices = new List<t_smd_ContractDevice>();
        //全局storeid
        private int _storeid;
        //全局设备
        private List<t_smd_Device> _devices;
        private t_smd_Device _device;
        //是否需要设备或者门店
        private bool _needSaveDevice;
        private bool _needSaveStore=false;//屏蔽门店合同

        private bool _oneDevice;
        private t_smd_Store _store;
        readonly List<t_StoreDataChangeLog> _contractLogs = new List<t_StoreDataChangeLog>();
        readonly List<t_StoreDataChangeLog> _deviceLogs = new List<t_StoreDataChangeLog>();

        //需要门店终止合同
        private bool _needStoreCancel = false;
        //需要设备终止合同
        private bool _needDeviceCancel = false;

        //营业时间
        public string OpenBusinessDate = "";

        //显示经销商信息
        public string oldDealerInfo = "";
        public string newDealerInfo = "";
        #endregion


        protected void Page_Load(object sender, EventArgs e)
        {

            #region 全局变量初始化
            DwzAssessment1.Category = "changeContract";
            btn_submit.Visible = TaskAPI.IsAllowSubmit;
            _storeid = TaskAPI.GetStoreId("storeid");
            if (_storeid == 0)
            {
                var storeMasterData = (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).ListFirst<t_StoreMasterData>();
                if (storeMasterData != null)
                {
                    _storeid = storeMasterData.StoreId??0;
                }
                
            }
            if (AksRequest.GetString("readonly") == "1")
            {
                var storeMasterData = (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).ListFirst<t_StoreMasterData>();
                if (storeMasterData != null && storeMasterData.StoreId != null)
                {
                    _storeid = storeMasterData.StoreId.Value;
                }
            }
            _store = StoreService.GetSmdStoreById(_storeid);
            var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
            step = TaskAPI.Step;

            uc_store_info2.Visible = false;
            tb_Transfer.Visible = false;
            StoreRegionReceive.Enabled = false;
            rpt_deviceContract.Visible = false;
            uc_store_info1.store = _store;
            uc_store_info1.IsCanEditAuthID = false;
            var deviceID = TaskAPI.GetVariableBySingleValue("DeviceID");
            if (deviceID != "0" && deviceID != "" && deviceID.Split('|').Count() == 1)
            {
                _oneDevice = true;
            }

            //chooseStoreTR.Visible = false;
            chooseDeviceTR.Visible = false;
            #endregion

            #region 获取父流程的业务数据
            var parentProcess = TaskAPI.GetVariableBySingleValue("ParentProcess");
            var parentIncident = TaskAPI.GetVariableBySingleValue("ParentIncident");
            var parentStoreMaster =
                (t_StoreMasterData._Process == parentProcess & t_StoreMasterData._Incident == parentIncident)
                    .ListFirst<t_StoreMasterData>();
            if (parentStoreMaster != null) {
                if (parentStoreMaster.NewFitment != null && (parentStoreMaster.NewFitment.Contains("升级") || parentStoreMaster.NewFitment.Contains("降级") || parentStoreMaster.NewFitment.Contains("关店")) && !parentStoreMaster.NewFitment.Contains("从IS升级"))
                {
                    _needStoreCancel = false; //true;
                }

                //20161220 update   
                if ((key.Equals(Constant.PROCESS_CHANGESTATUS) || key.Equals(Constant.PROCESS_TRANSFER)))
                {
                    _needDeviceCancel = true;
                }
            }

            #endregion

            #region 获取设备
            if (_oneDevice)
            {
                _device = DeviceService.GetSmdDeviceById(Utils.StrToInt(deviceID, 0));
            }
            else
            {
                _devices = DeviceService.FindByStoreId(_storeid);
            }
            #endregion

            #region 判断是新建的还是自动启的，并且判断保存什么类型的合同，如果不是就全都可以。
            if (key != "" && key != "ChangeOther")
            {
                #region MyRegion
                //Modified by Tony 20160509 -- || key.Equals(Constant.PROCESS_CHANGECONTRACT)
                if (key.Equals(Constant.PROCESS_TRANSFER) || key.Equals(Constant.PROCESS_CHANGESTATUS) || key.Equals(Constant.PROCESS_CHANGECONTRACT))
                {
                    _needSaveDevice = true;
                }

                if ((key.Equals(Constant.PROCESS_STORE) || key.Equals(Constant.PROCESS_CHANGEDEALER)))
                {
                    if (_oneDevice)
                    {
                        _needSaveDevice = true;
                    }
                }

                if (key.Equals(Constant.PROCESS_STORE) || key.Equals(Constant.PROCESS_CHANGEDEALER) || (key.Equals(Constant.PROCESS_CHANGELEVEL) && !_store.StoreType.Contains("IS") && _store.StoreStatus != "关闭"))
                    _needSaveStore = false; // true;

                if (key.Equals(Constant.PROCESS_TRANSFER))
                {
                    var oldStoreID = Utils.StrToInt(TaskAPI.GetVariableBySingleValue("OldStoreID"), 0);
                    uc_store_info2.Visible = true;
                    uc_store_info2.store = StoreService.GetSmdStoreById(oldStoreID);
                    uc_store_info1.isNew = "new";
                    uc_store_info1.IsShowDeivceList = false;
                    uc_store_info2.isNew = "old";
                    uc_store_info2.IsShowDeivceList = false;
                    uc_store_info2.IsCanEditAuthID = false;
                    tb_Transfer.Visible = true;
                    var oldDealer = DealerService.GetById(uc_store_info2.store.DealerID.Value);
                    var newDealer = DealerService.GetById(_store.DealerID.Value);
                    oldDealerInfo = "--前经销商code:" + oldDealer.DealerCode + "  经销商名称:" + oldDealer.Name;
                    newDealerInfo = "--现经销商code:" + newDealer.DealerCode + "  经销商名称:" + newDealer.Name;

                }
                #endregion                
            }
            else
            {
                if (_devices.Count == 0 && _device == null)
                {
                    _needSaveDevice = false;
                }
                else
                {
                    _needSaveDevice = true;
                }
                if (_store.StoreStatus != "关闭") {
                    _needSaveStore = false; //true;
                }
            }



            if (parentStoreMaster != null && (parentStoreMaster.NewFitment == "翻新" || parentStoreMaster.NewFitment == "仅调色机申请"
                || (parentStoreMaster.NewFitment != null && parentStoreMaster.NewFitment.Contains("关店") && _store.StoreStatus == "关闭"))) 
            {
                _needSaveStore = false;
            }

            if (_store != null && _store.StoreType != "DDCN" && _store.StoreType != "DCSS" && !TaskAPI.Summary.Contains("IS升级"))
            {
                _needSaveStore = false;
            }

            //if (_needSaveStore || _needStoreCancel)
            //{设备合同版本号
            //    storeContract.Style.Add("display", "");
            //    chooseStoreTR.Visible = true;
            //} 2016-11-04 取消门店合同
            if (_needSaveDevice)
            {
                //20161228 三方转移只有转入转出门店类型都为MT签设备合同
                if (key.Equals(Constant.PROCESS_TRANSFER) && uc_store_info1.store.StoreType == "MT") {
                    rpt_deviceContract.Visible = true;
                }

                //20170104  && _store.StoreType == "MT"  由于有已经在代办事项的数据需要正常显示合同，所以这里需要去掉判断（因为非MT的不会发起合同,所以此处可开放条件）
                if (key.Equals(Constant.PROCESS_STORE))
                {
                    rpt_deviceContract.Visible = true;
                }

                Logging.GetLogger().Error("uc_store_info1-StoreType：" + uc_store_info1.store.StoreType + "uc_store_info2.store.StoreType:" + uc_store_info2.store.StoreType + "/_store.StoreType:" + _store.StoreType);
                chooseDeviceTR.Visible = true;
            }
            //cb_storeContract.Visible = false;
            cb_deviceContract.Visible = false;
            #endregion

            #region 加载合同log数据
            var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);
            var lastChangelogs = ChangeLogService.GetLastChangeLogs(assIds);
            if (lastChangelogs != null && lastChangelogs.Count > 0)
            {
                foreach (var log in lastChangelogs)
                {
                    switch (log.Category)
                    {
                        case "ChangeDeviceContract":
                            _deviceLogs.Add(log);
                            break;
                        //case "ChangeStoreContract":
                        //    _contractLogs.Add(log);
                        //    break;   2016-11-04 取消门店合同
                    }
                }
            }
            #endregion

            #region 初始化设备或者门店合同，并加载合同log数据
            var contract = ContractService.GetContractByStoreID(_storeid);
            t_smd_ContractDevice contractDevice = null;
            StoreCancelContract.Visible = false;

            #region   2016-11-04   取消门店合同及门店终止合同
            //如果需要门店合同
            //if (_needSaveStore && _store.StoreStatus != "关闭" && !_store.StoreType.Contains("IS") || (TaskAPI.Summary.Contains("IS升级") && key == Constant.PROCESS_STORE))
            //{

            //    if (_store.StoreStatus != "关闭" && contract == null)
            //    {
            //        contract = new t_smd_Contract
            //        {
            //            StoreID = _storeid,
            //            AuthID = _store.AuthID
            //        };
            //        if (_store.StoreID != 0)
            //        {
            //            Storage.Save(Storage.Context3, contract);
            //        }
            //    }
            //    var _logs = _contractLogs.Where(s => s.DataID == contract.ContractID.ToString()).ToList();
            //    contract = DataHelper<t_smd_Contract>.Reload(contract, _logs);
            //}

            //if (_needStoreCancel)
            //{
            //    var contractCancel = ContractService.GetContractCancelByStoreID(_storeid);
            //    if (contractCancel != null)
            //    {
            //        StoreCancelContract.Visible = true;
            //        //DataStoreCancelViewBind(contractCancel);
            //    }
            //}
            #endregion
            //如果需要设备合同
            if (_needSaveDevice)
            {
                if (_oneDevice && _device != null)
                {
                    //如果是eapprove发起的说明肯定需要新建一张设备合同
                    if (parentStoreMaster !=null && parentStoreMaster.IsEapprove == true)
                    {
                        var type = "";
                        switch (parentStoreMaster.ApplicationType)
                        {
                            case "新机安装(STD)":
                                type = "调色机发放协议-标准购机";
                                break;
                            case "旧机转让(STD)":
                                type = "调色机发放协议-标准购机旧机投放";
                                break;
                            case "新机安装(DIR)":
                                type = "调色机发放协议-直接购机";
                                break;
                            case "旧机转让(DIR)":
                                type = "调色机发放协议-直接购机旧机投放";
                                break;

                        };

                        if (StoreService.GetSmdStoreById(_storeid).StoreType.Contains("卖场"))
                        {
                            if (_device.DeliveryType == "STD")
                            {
                                type = "调色机发放协议-MT";
                            }
                            else if (_device.DeliveryType == "")
                            {
                                type = "调色机发放协议-直接购机-卖场";
                            }
                        }

                        contractDevice = ContractDeviceService.getContractDeviceByDeviceId(_device.DeviceID);

                        if (_storeid != 0 && (contractDevice == null)) 
                        {
                            contractDevice = new t_smd_ContractDevice
                            {
                                StoreID = _storeid,
                                DeviceID = _device.DeviceID,
                                DeviceFixAssetNo = _device.FullSetSN,
                                DeviceContractType = type
                            };

                            //Add by Tony 20160513
                            //Logging.GetLogger().Info(string.Format("1.StoreID:{0} DeviceID:{1}  DeviceFixAssetNo:{2}  DeviceContractType:{3}", _storeid, _device.DeviceID
                            //    , _device.FullSetSN, type));
                            Storage.Save(Storage.Context3, contractDevice);
                        }
                    }
                    //如果是从设备报废库存流程来的，说明没有设备合同不需要新建一张。
                    if (key.Equals(Constant.PROCESS_CHANGESTATUS) || key.Equals(Constant.PROCESS_TRANSFER))
                    {
                        contractDevice = ContractDeviceService.getContractDeviceByDeviceId(_device.DeviceID);
                    }

                    if (contractDevice != null) {
                        var LIST = _deviceLogs.Where(d => d.DataID == contractDevice.ContractDeviceID.ToString(CultureInfo.InvariantCulture) || d.DataID == "0").OrderBy(o => o.LogID).ToList();
                        
                        DataHelper<t_smd_ContractDevice>.Reload(contractDevice, LIST);
                        ContractDevices.Add(contractDevice);
                    }
                }
                else
                {
                    foreach (var device in _devices)
                    {
                        contractDevice = ContractDeviceService.getContractDeviceByDeviceId(device.DeviceID);
                        if (contractDevice == null && device.Status == "使用")
                        {
                            contractDevice = new t_smd_ContractDevice()
                            {
                                StoreID = _storeid,
                                DeviceID = device.DeviceID,
                                DeviceFixAssetNo = device.FullSetSN
                            };

                            //Add by Tony 20160513
                            //Logging.GetLogger().Debug(string.Format("2.StoreID:{0} DeviceID:{1}  DeviceFixAssetNo:{2}", _storeid, _device.DeviceID
                            //    , _device.FullSetSN));
                            Storage.Save(Storage.Context3, contractDevice);
                        }

                        if (contractDevice != null)
                        {
                            DataHelper<t_smd_ContractDevice>.Reload(contractDevice, _deviceLogs.Where(d => d.DataID == contractDevice.ContractDeviceID.ToString(CultureInfo.InvariantCulture) || d.DataID == "0").ToList());
                            ContractDevices.Add(contractDevice);
                        }
                    }
                }

                rpt_deviceContract.DataSource = ContractDevices;
                rpt_deviceContract.DataBind();
            }
            #endregion

            #region 判断需要展示终止合同
            StoreCancelContract.Visible = false;//_needStoreCancel;
            oneDevieCancel.Visible = _needDeviceCancel;
            if (key.Equals(Constant.PROCESS_CHANGELEVEL) && _store != null && (_store.StoreStatus == "关闭" || (!_store.StoreType.Contains("DDCN") || !_store.StoreType.Contains("DCSS"))))
            {
                storeContract.Visible = false;
            }
            #endregion

            btn_save.Visible = false;
            if (!IsPostBack)
            {
                
                if (ReadOnly(contractDevice)) return;
                

                if (key.Equals(Constant.PROCESS_STORE)) 
                {
                    if(_store.OpenBusinessDate != null){
                        OpenBusinessDate = _store.OpenBusinessDate.Value.ToString("yyyy-MM-dd");
                    }
                    
                }

                if (IsOverFlow)
                {
                    btn_submit.Visible = false;
                    ScriptManager.RegisterStartupScript(this, GetType(), "info_tip", "$.jBox.prompt('" + string.Format("该表单正在被“{0}”处理，请稍后再试。", RobUser) + "', 'info');", true);
                    return;
                }

                InitDropDownList();
                ShowCancelInfo(true);
                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");

                #region Submit Data
                if (TaskAPI.Step == "Submit Data")
                {
                    //cb_storeContract.Visible = false;//true; 2016-11-04 取消门店合同
                    cb_deviceContract.Visible = true;
                    cb_deviceContract.Checked = true;//2016-11-28  默认设备合同勾选

                    btn_save.Visible = true;
                    if (key == "" || key == Constant.PROCESS_CHANGEOTHER)
                    {
                        uc_store_info1.IsCanEditAuthID = true;
                    }
                    if (_store != null && _store.StoreID != 0 && _needSaveStore)
                    {
                        var storeMasterDate = (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).ListFirst<t_StoreMasterData>();
                        if (storeMasterDate != null) { 
                            uc_store_info1.IsCanEditAuthID = false;
                        }

                        ViewStoreData(contract, true);
                    }
                    if (key == Constant.PROCESS_TRANSFER)
                    {
                        //ViewTransferData(contractDevice, true);
                    }
                    if (!String.IsNullOrEmpty(TaskAPI.GetVariableBySingleValue("Checked")))
                    {
                        assessment.Visible = true;
                    }
                }
                #endregion

                #region 审批环节
                else
                {
                    cb_deviceContract.Visible = true;
                    cb_deviceContract.Checked = true;//2016-11-28  默认设备合同勾选

                    assessment.Visible = true;
                    changelogs.Visible = true;
                    uc_change_field1.AssessmentIDs = AssessmentService.GetIdsByTaskApi(TaskAPI);
                    #region 加载数据并显示
                    // 门店数据
                    var storeMasterData = (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).ListFirst<t_StoreMasterData>();
                    if (storeMasterData == null)
                    {
                        btn_submit.Visible = false;
                        ScriptManager.RegisterStartupScript(this, GetType(), "info_tip", "$.jBox.tip('加载数据失败，请关闭页面重新打开！', 'info');", true);
                        return;
                    }
                    hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                    hl_ExportPdf.Visible = true;
                    uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");
                    
                    #region Data Check
                    if (TaskAPI.Step == "Data Check" || TaskAPI.Step == "Manager Approve")
                    {
                        if (_needSaveStore)
                        {
                            ViewStoreData(contract, true);
                        }

                        if (TaskAPI.Step == "Manager Approve")
                        {
                            StoreRegionReceive.Enabled = true;
                            FileUpload.Visible = true;
                            AjaxUpload1.UploadID = "deviceUpload";
                        }
                        if (key == Constant.PROCESS_TRANSFER)
                        {
                            //ViewTransferData(contractDevice, true);
                        }
                    }
                    #endregion
                    else
                    {
                        if (TaskAPI.Step == "DMO Commit")
                        {
                            ShowCancelInfo(false);
                            DwzAssessment1.Category = null;
                            if (_needSaveStore)
                            {
                                ViewStoreData(contract, false);
                            }
                            if (key == Constant.PROCESS_TRANSFER)
                            {
                                //ViewTransferData(contractDevice, false);
                            }
                        }
                        else
                        {
                            if (_needSaveStore)
                            {
                                ViewStoreData(contract, false);
                            }
                            if (key == Constant.PROCESS_TRANSFER)
                            {
                                //ViewTransferData(contractDevice, true);
                            }
                        }

                        assessment.Visible = true;
                        var assessments = (t_Assessment.process == TaskAPI.Process
                            & t_Assessment.incident == TaskAPI.Incident).List<t_Assessment>();
                        changelogs.Visible = true;

                        Logs = (t_StoreDataChangeLog._AssessmentID.In(assessments.Select(t => t.ID))).List<t_StoreDataChangeLog>(null, " logid desc ");
                    }
                    #endregion
                }
                #endregion
            }
        }

        #region 流程Send方法
        private bool Send(ref string returnMsg)
        {
            var flag = false;
            if (DwzAssessment1.Assessment.Remark == "")
            {
                if (DwzAssessment1.Assessment.Opinion == "2")
                {
                    returnMsg = "如果驳回此流程,请在状态备注中填写放弃流程的原因";
                    return false;
                }
                if (DwzAssessment1.Assessment.Opinion == "0")
                {
                    returnMsg = "如果退回此流程,请在状态备注中填写退回的原因";
                    return false;
                }
                
            }

            try
            {
                #region 数据验证
                if (TaskAPI.IsBeginStep && TaskAPI.IsAllowSubmit) // 如果是退回的情况，不存在验证
                {
                    if (_storeid == 0)
                    {
                        returnMsg = "请选择门店";
                        return false;
                    }
                    if (TaskAPI.Summary.Contains("IS升级") && _store.StoreType.Contains("IS"))
                    {
                        returnMsg = "发现此门店还是IS门店,请先完成门店信息变更流程";
                        return false;
                    }
                }
                else if (TaskAPI.Step == "Manager Approve")
                {

                    if ((StoreRegionReceive.Checked) && (!AjaxUpload1.IsHaveAttachment))
                    {
                        returnMsg = "请上传收到快递后的确认邮件";
                        return false;
                    }

                }
                #endregion

                #region 引擎传值
                if (TaskAPI.Step == "Submit Data")
                {
                    var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                    TaskAPI["MailSubject"] = "授权号:" + _store.AuthID + " -- " + _store.StoreType;
                    TaskAPI["IsContractChange"] = 1;
                    // 空的话，是手动发起的流程
                    if (string.IsNullOrEmpty(key) || key == Constant.PROCESS_CHANGEOTHER)
                    {
                        TaskAPI["BlankVlue"] = _storeid;
                    }
                    if (_device == null)
                    {
                        TaskAPI["DeviceID"] = "0";
                    }
                    else
                    {
                        TaskAPI["DeviceID"] = _device.DeviceID;
                    }
                    TaskAPI["Remark_by_Initiator"] = DwzAssessment1.Assessment.Remark;
                    if (TaskAPI.Summary.Contains("退回"))
                    {
                        TaskAPI.Summary = "合同信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + _store.AuthID;
                    }
                    else
                    {
                        TaskAPI.Summary = "合同信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "-" + _store.Region + "|" + _store.AuthID;
                    }


                    if (_oneDevice && _device != null)
                    {
                        TaskAPI.Summary += "|" + _device.FullSetSN;
                    }
                    else if (_devices.Count > 0)
                    {
                        foreach (var device in _devices)
                        {
                            TaskAPI.Summary += "|" + device.FullSetSN;
                        }
                    }
                }
                else
                {
                    if (uc_store_info1.store.DealerID != null)
                    {
                        var dealer = DealerService.GetById(uc_store_info1.store.DealerID.Value);
                        var summary = "|" + _store.AuthID + "|" + dealer.DealerCode;
                        TaskAPI["ApproveResult"] = DwzAssessment1.Assessment.Opinion;
                        TaskAPI["TaskID"] = TaskAPI.TaskID;
                        switch (TaskAPI.Step)
                        {
                            #region Data Check
                            case "Data Check":
                                TaskAPI["Checked"] = DwzAssessment1.Assessment.Opinion;
                                if (DwzAssessment1.Assessment.Opinion == "1")
                                {
                                    TaskAPI.Summary = "全国合同负责人审核/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                                    if (_oneDevice)
                                    {
                                        TaskAPI.Summary += "|" + _device.FullSetSN;
                                    }
                                    else if (_devices.Count > 0)
                                    {
                                        foreach (var deivce in _devices)
                                        {
                                            TaskAPI.Summary += "|" + deivce.FullSetSN;
                                        }
                                    }
                                }
                                else
                                {
                                    TaskAPI.Summary = "(退回)提交合同信息变更/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                                    if (_oneDevice)
                                    {
                                        TaskAPI.Summary += "|" + _device.FullSetSN;
                                    }
                                    else if (_devices.Count > 0)
                                    {
                                        foreach (var device in _devices)
                                        {
                                            TaskAPI.Summary += "|" + device.FullSetSN;
                                        }
                                    }
                                }
                                break;
                            #endregion

                            #region Manager Approve
                            case "Manager Approve":
                                TaskAPI["Approved"] = DwzAssessment1.Assessment.Opinion;
                                if (DwzAssessment1.Assessment.Opinion == "1")
                                {
                                    TaskAPI.Summary = "合同信息DMO导入核查/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                                    if (_oneDevice)
                                    {
                                        TaskAPI.Summary += "|" + _device.FullSetSN;
                                    }
                                    else if (_devices.Count > 0)
                                    {
                                        foreach (var device in _devices)
                                        {
                                            TaskAPI.Summary += "|" + device.FullSetSN;
                                        }
                                    }
                                }
                                else
                                {
                                    TaskAPI.Summary = "(退回)合同信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                                    if (_oneDevice)
                                    {
                                        TaskAPI.Summary += "|" + _device.FullSetSN;
                                    }
                                    else if (_devices.Count > 0)
                                    {
                                        foreach (var device in _devices)
                                        {
                                            TaskAPI.Summary += "|" + device.FullSetSN;
                                        }
                                    }
                                }
                                break;
                            #endregion

                            #region DMO Commit
                            case "DMO Commit":
                                returnMsg = "数据更新到主数据库中时出现错误，请跟踪并处理。";
                                TaskAPI["Commited"] = DwzAssessment1.Assessment.Opinion;
                                if (DwzAssessment1.Assessment.Opinion == "0")
                                {
                                    TaskAPI.Summary = "(退回)全国合同负责人审核/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                                    if (_oneDevice)
                                    {
                                        TaskAPI.Summary += "|" + _device.FullSetSN;
                                    }
                                    else if (_devices.Count > 0)
                                    {
                                        foreach (var device in _devices)
                                        {
                                            TaskAPI.Summary += "|" + device.FullSetSN;
                                        }
                                    }
                                }
                                break;
                            #endregion
                        }
                    }
                }
                #endregion

                #region 提交步骤
                Storage.TransactionExecute(o =>
                {
                    SaveCancelInfo();
                    #region 业务流程、审批意见记录

                    t_Assessment ass = DwzAssessment1.Assessment;
                    var lastAss = (t_Assessment.incident == TaskAPI.Incident & t_Assessment.opinionText != "暂存" & t_Assessment.process == TaskAPI.Process).ListFirst<t_Assessment>("time desc");
                    if ((lastAss != null && lastAss.Step != TaskAPI.Step) || lastAss == null)
                    {
                        Storage.Save(Storage.Context1, ass);
                    }
                    else
                    {
                        Logging.GetLogger().Info("=================表单已重复提交======================");
                        Logging.GetLogger().Info("TaskAPI.Step:" + TaskAPI.Step);
                        Logging.GetLogger().Info("TaskAPI.UserFullName:" + TaskAPI.UserFullName);
                        Logging.GetLogger().Info("时间：" + DateTime.Now);
                        Logging.GetLogger().Info("UserAPI.UserName:" + UserAPI.UserName);
                        Logging.GetLogger().Info("======================================================");
                        throw new Exception("该表单的步骤已经提交过了，请联系IT。");
                    }
                    Storage.Save(Storage.Context1, ass);
                    
                    var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                    #endregion

                    #region “Submit Data”步骤
                    if (TaskAPI.Step == "Submit Data")
                    {
                        var storeMasterData = (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).ListFirst<t_StoreMasterData>();
                        if (storeMasterData == null) { 
                            storeMasterData = new t_StoreMasterData
                            {
                                SubmitDate = DateTime.Now,
                                Creator = TaskAPI.UserName,
                                ApplicationNO = uc_head1.applicationNo,
                                Process = TaskAPI.Process,
                                Incident = TaskAPI.Incident,
                                StoreId = _storeid,

                                AreaName = uc_store_info1.store.Region,
                                ProvinceName = uc_store_info1.store.Province,
                                CityName = uc_store_info1.store.CityName,
                                BusinessProcess = ass.BusinessProcess,
                                BusinessKey = ass.BusinessKey
                            };
                            Storage.Save(Storage.Context1, storeMasterData);
                            BusinessService.SaveChildProcess(TaskAPI, ass, "active");
                            if (key == Constant.PROCESS_CHANGEOTHER && !TaskAPI.Summary.Contains("退回"))
                            {
                                TaskAPI.Summary = "合同信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + " - " + ass.BusinessKey + "|" + _store.AuthID;
                            }
                        }
                        SaveChangeLog(ass.ID);

                        if (key.Equals(Constant.PROCESS_CHANGEOTHER))
                        {
                            BusinessService.SaveChildProcess(TaskAPI, ass, "active");

                            var store = StoreService.GetSmdStoreById(_storeid);
                            var dealer = DealerService.GetById(store.DealerID.Value);
                            BusinessService.saveProcessRelation(TaskAPI, ass, store, _device, dealer, null, null, _devices, null);
                        }
                    }
                    #endregion

                    #region Data Check步骤
                    if (TaskAPI.Step == "Data Check")
                    {
                        SaveChangeLog(ass.ID);
                    }
                    #endregion

                    #region Manager Approve步骤
                    if (TaskAPI.Step == "Manager Approve")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "2")
                        {

                            flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));
                            BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                        }
                        else
                        {
                            SaveChangeLog(ass.ID);
                            (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).Edit<t_StoreMasterData>(p =>
                            {
                                step = p.Step = TaskAPI.Step;
                            });
                        }


                    }
                    #endregion

                    #region “DMO Commit”步骤
                    if (TaskAPI.Step == "DMO Commit")
                    {

                        if (DwzAssessment1.Assessment.Opinion == "2")
                        {
                            flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));
                            BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                        }
                        else if (DwzAssessment1.Assessment.Opinion == "1")
                        {

                            #region 变更日志
                            Mapper.CreateMap<t_StoreDataChangeLog, t_smd_StoreDataChangeLog>();

                            var assids = AssessmentService.GetIdsByTaskApi(TaskAPI);
                            var mdcChangelogs = ChangeLogService.GetLastChangeLogs(assids);

                            var smdChangelogs = Mapper.Map<IList<t_StoreDataChangeLog>, List<t_smd_StoreDataChangeLog>>(mdcChangelogs);
                            foreach (var smdChangelog in smdChangelogs)
                            {
                                smdChangelog.EntityState._FieldState.Remove("LogID");
                            }
                            // ReSharper disable once CoVariantArrayConversion
                            Storage.Save(Storage.Context3, smdChangelogs.ToArray());
                            #endregion

                            #region 更新主数据
                            var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);
                            var lastChangelogs = ChangeLogService.GetLastChangeLogs(assIds);
                            if (lastChangelogs != null && lastChangelogs.Count > 0)
                            {
                                foreach (var log in lastChangelogs)
                                {
                                    if (log.Category == "ChangeDeviceContract")
                                        _deviceLogs.Add(log);
                                    else if (log.Category == "ChangeStoreContract")
                                        _contractLogs.Add(log);
                                }
                            }


                            //2016-11-08 取消门店合同
                            //if (_needSaveStore)
                            //{
                            //    var contract = (t_smd_Contract._StoreID == _storeid.ToString(CultureInfo.InvariantCulture)).ListFirst<t_smd_Contract>(Storage.Context3);
                            //    contract = DataHelper<t_smd_Contract>.Reload(contract, _contractLogs);
                            //    Storage.Save(Storage.Context3, contract);
                            //}

                            if (_needSaveDevice)
                            {
                                foreach (var contractDevice in ContractDevices)
                                {
                                    Storage.Save(Storage.Context3, contractDevice);
                                }
                            }

                            #endregion

                            (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).Edit<t_StoreMasterData>(p =>
                            {
                                step = p.Step = "Finish";
                            });
                            BusinessService.SaveChildProcess(TaskAPI, DwzAssessment1.Assessment, "Finish");
                        }
                    }
                    #endregion


                    if (DwzAssessment1.Assessment.Opinion != "2")
                    {
                        // 变更列表
                        TaskAPI["Content"] = ChangeLogService.GenerateExcel(TaskAPI);
                        flag = TaskAPI.Send();
                    }
                    if (!flag) o.Rollback();

                    #region 如果数据库写入成功且流程发起成功的情况，将业务表数据与流程实例号进行关联
                    if (TaskAPI.Step == "Submit Data")
                    {
                        (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                        {
                            p.Incident = TaskAPI.Incident;
                        });

                        (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 & t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                        {
                            p.Incident = TaskAPI.Incident;
                        });
                    }
                    #endregion
                });
                #endregion


            }
            catch (Exception ex)
            {
                if (returnMsg == "")
                    returnMsg = "提交失败，请尝试重新登录或重新打开页面，如果还是不能提交，请联系管理员";

                Logging.GetLogger().Error("调用BatchStore方法Send_Click出错：" + ex);
                flag = false;
            }
            return flag;
        }
        #endregion

        #region 展示门店合同数据

        /// <param name="contract"></param>
        /// <param name="isedit">是否能编辑</param>
        private void ViewStoreData(t_smd_Contract contract, bool isedit)
        {
            //l_StoreParty.Visible = true;

            //if (isedit)
            //{
            //    DataStoreEditBind(contract);
            //}
            //else
            //{
                ddl_StoreContractType.Visible = false;
                
                tb_StoreContractBeginDate.Visible = false;
                cb_HasAwardContract.Disabled = true;
                tb_AwardContractEndDate.Visible = false;
                cb_HasTransferContract.Disabled = true;
                tb_TransferFromStoreSN.Visible = false;
                tb_TransferToStoreSN.Visible = false;
                tb_TransferContractDate.Visible = false;
                cb_HasRenewContract.Disabled = true;
                tb_RenewContractBeginDate.Visible = false;
                tb_RenewContractEndDate.Visible = false;
                tb_ToStoreEms.Visible = false;
                StoreNature.Visible = false;
                StoreAffiliation.Visible = false;
                tb_StoreFileNO.Visible = false;
                StoreExpressDate.Visible = false;
                StoreEms.Visible = false;
                StoreFinance.Visible = false;
                StoreArchive.Visible = false;
                StoreRegionReceive.Enabled = false;
                Remark.Visible = false;
                tb_StoreNotSignReason.Visible = false;
                ddl_StoreContractSN.Visible = false;
                ddl_StoreParty.Visible = false;

                DataStoreViewBind(contract);
            // } 屏蔽门店合同数据 2016-11-04
        }
        #endregion

        //#region 展示设备三方转移合同数据

        //private void ViewTransferData(t_smd_ContractDevice_Cancel contractDevice, bool isedit)
        //{
        //    if (isedit)
        //    {
        //        tb_PartyACustomer.Text = contractDevice.PartyACustomer;
        //        tb_PartyBCustomer.Text = contractDevice.PartyBCustomer;
        //        tb_FineAmount.Text = contractDevice.FineAmount.ToString("N");
        //        tb_TransferAmount.Text = contractDevice.TransferAmount.ToString("N");
        //    }
        //    else
        //    {
        //        tb_PartyACustomer.Visible = false;
        //        tb_PartyBCustomer.Visible = false;
        //        tb_FineAmount.Visible = false;
        //        tb_TransferAmount.Visible = false;

        //        l_PartyACustomer.Text = contractDevice.PartyACustomer;
        //        l_PartyBCustomer.Text = contractDevice.PartyBCustomer;
        //        l_FineAmount.Text = contractDevice.FineAmount.ToString("N");
        //        l_TransferAmount.Text = contractDevice.TransferAmount.ToString("N");
        //    }
        //}

        //#endregion

        #region 绑定各选项
        private void InitDropDownList()
        {
            var configService = new ConfigService();
            #region 门店合同类型
            //DataTable storeContracts = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_DMHTLX') order by seq").Tables[0];
            //ddl_StoreContractType.AppendDataBoundItems = true;
            //foreach (DataRow row in storeContracts.Rows)
            //{
            //    ddl_StoreContractType.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            //}   2016-11-04 取消门店合同
            #endregion

            #region 设备合同类型
            DataTable deviceContracts = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_SBHTLX') order by seq").Tables[0];
            //DeviceCancelContractType.AppendDataBoundItems = true;
            //foreach (DataRow row in deviceContracts.Rows)
            //{
            //    DeviceCancelContractType.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            //}
            #endregion

            #region 合同性质
            var nature = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_HTXZ') order by seq").Tables[0];
            StoreNature.AppendDataBoundItems = true;
            ddl_StoreCancelNature.AppendDataBoundItems = true;
            foreach (DataRow row in nature.Rows)
            {
                StoreNature.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
                ddl_StoreCancelNature.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            s_DeviceCancelNature.AppendDataBoundItems = true;
            foreach (DataRow row in nature.Rows)
            {
                s_DeviceCancelNature.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 合同归属
            var affiliation =
                configService.GetList("ParentId = (select configid from t_smd_Config where code='S_HTGS') order by seq").Tables[0];
            //门店
            StoreAffiliation.AppendDataBoundItems = true;
            //设备
            s_DeviceCancelAffiliation.AppendDataBoundItems = true;
            //门店终止
            ddl_StoreCancelAffiliation.AppendDataBoundItems = true;

            foreach (DataRow row in affiliation.Rows)
            {
                s_DeviceCancelAffiliation.Items.Add(new ListItem(row["Name"].ToString(), row["Value"].ToString()));
                StoreAffiliation.Items.Add(new ListItem(row["Name"].ToString(), row["Value"].ToString()));
                ddl_StoreCancelAffiliation.Items.Add(new ListItem(row["Name"].ToString(), row["Value"].ToString()));
            }
            #endregion

            #region 门店合同版本号
            DataTable StoreContractSN = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_HTBBH') order by seq").Tables[0];
            ddl_StoreContractSN.AppendDataBoundItems = true;
            foreach (DataRow row in StoreContractSN.Rows)
            {
                ddl_StoreContractSN.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }

            #endregion

            #region 设备合同版本号
            DataTable DeviceConractSN = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_SBBBH') order by seq").Tables[0];
            //DeviceCancelContractSN.AppendDataBoundItems = true;
            //ddl_StoreCancelContractSN.AppendDataBoundItems = true;
            //ddl_StoreCancelContractSN.AppendDataBoundItems = true;
            foreach (DataRow row in DeviceConractSN.Rows)
            {
               // DeviceCancelContractSN.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
                //ddl_StoreCancelContractSN.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 合同甲方

            var ContractParty = configService.GetList("ParentId = (select configid from t_smd_Config where code = 'HTJF')").Tables[0];
            DeviceCancelParty.AppendDataBoundItems = true;
            StoreCancelParty.AppendDataBoundItems = true;
            ddl_StoreParty.AppendDataBoundItems = true;
            foreach (DataRow row in ContractParty.Rows)
            {
                ddl_StoreParty.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
                DeviceCancelParty.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
                StoreCancelParty.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }

            #endregion
        }
        #endregion

        #region 保存log数据
        protected void SaveChangeLog(string assID)
        {

            #region 记录门店合同变更的字段     （隐藏门店合同变更 2016-11-04）
            //if (_needSaveStore && _store.StoreStatus != "关闭") { 
                //    var store = (t_smd_Store._StoreID == _storeid).ListFirst<t_smd_Store>(Storage.Context3);
                //    var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                //    var existingContractChangelogs = ChangeLogService.GetLastChangeLogs(TaskAPI).Where(t => t.Category == "ChangeStoreContract").ToList();
                //    var contract = (t_smd_Contract._StoreID == _storeid).ListFirst<t_smd_Contract>(Storage.Context3) ??
                //                   new t_smd_Contract();
                //    DataHelper<t_smd_Contract>.Reload(contract, existingContractChangelogs);
                //    var newContract = (t_smd_Contract)contract.CloneObject();
                //    newContract.StoreID = _storeid;
                //    newContract.AuthID = store.AuthID;

                //    newContract.StoreContractSN = ddl_StoreContractSN.SelectedValue;
                //    newContract.StoreContractType = ddl_StoreContractType.SelectedValue;
                //    newContract.StoreContractBeginDate = Utils.StrToDateTimeN(tb_StoreContractBeginDate.Text);

                //    newContract.AwardContractBeginDate = Utils.StrToDateTimeN(tb_AwardContractBeginDate.Text);
                //    newContract.AwardContractEndDate = Utils.StrToDateTimeN(tb_AwardContractEndDate.Text);

                //    newContract.TransferFromStoreSN = tb_TransferFromStoreSN.Text;
                //    newContract.TransferToStoreSN = tb_TransferToStoreSN.Text;
                //    newContract.TransferContractDate = Utils.StrToDateTimeN(tb_TransferContractDate.Text);

                //    newContract.RenewContractBeginDate = Utils.StrToDateTimeN(tb_RenewContractBeginDate.Text);
                //    newContract.RenewContractEndDate = Utils.StrToDateTimeN(tb_RenewContractEndDate.Text);
                //    newContract.StoreFileNO = tb_StoreFileNO.Text;

                //    newContract.StoreNature = StoreNature.SelectedValue;
                //    newContract.StoreAffiliation = StoreAffiliation.SelectedValue;
                //    newContract.StoreParty = ddl_StoreParty.SelectedValue;
                //    newContract.StoreCopies = 3;
                //    if (!string.IsNullOrEmpty(StoreExpressDate.Text))
                //    {
                //        newContract.StoreExpressDate = DateTime.Parse(StoreExpressDate.Text);
                //    }
                //    newContract.StoreEms = StoreEms.Text;
                //    newContract.StoreFinance = StoreFinance.Checked;
                //    newContract.StoreArchive = StoreArchive.Text;
                //    newContract.Remark = Remark.Text;
                //    newContract.StoreRegionReceive = StoreRegionReceive.Checked;

                //    newContract.ToStoreEms = tb_ToStoreEms.Text;

                //    if (newContract.StoreNature == "无法签署")
                //    {
                //        newContract.StoreNotSignReason = tb_StoreNotSignReason.Text;
                //    }
                //    if (key.Equals(Constant.PROCESS_CHANGELEVEL)&&_store.StoreStatus == "关闭")
                //    {
                   
                //    }else
                //    {
                //        if (newContract.ContractID == 0)
                //        {
                //            newContract.EntityState._Loaded = false;
                //            newContract.EntityState._FieldState.Remove("ContractID");
                //            Storage.Save(Storage.Context3, newContract);
                //        }
                //        else
                //        {
                //            var changeContractlogs = DataHelper<t_smd_Contract>.GetChangeLogs(contract, newContract,
                //                newContract.GetChangeFields(), "ContractID", UserAPI.UserFullName, assID, "ChangeStoreContract");
                //            // ReSharper disable once CoVariantArrayConversion
                //            Storage.Save(Storage.Context1, changeContractlogs.ToArray());
                //        }
                //    }
                //}
                #endregion
            
            #region 记录设备合同的变更字段
            if (ContractDevices.Count > 0 && _needSaveDevice)
            {

                foreach (var deviceContract in ContractDevices)
                {

                    if (deviceContract.ContractDeviceID != 0)
                    {
                        var existingDeviceChangelogs = ChangeLogService.GetLastChangeLogs(TaskAPI).Where(t => t.Category == "ChangeDeviceContract" & t.DataID == deviceContract.ContractDeviceID.ToString(CultureInfo.InvariantCulture)).ToList();
                        DataHelper<t_smd_ContractDevice>.Reload(deviceContract, existingDeviceChangelogs);
                    }
                    var newDeviceContract = (t_smd_ContractDevice)deviceContract.CloneObject();
                    foreach (RepeaterItem item in rpt_deviceContract.Items)
                    {
                        var deviceID = item.FindControl("DeviceID") as HtmlInputHidden;
                        if (deviceContract.DeviceID != Utils.StrToInt(deviceID.Value, 0)) continue;
                        var deviceContractSn = item.FindControl("d_DeviceContractSN") as HtmlSelect;
                        var deviceFixAssetNo = item.FindControl("DeviceFixAssetNo") as HtmlInputText;
                        var deviceContractBeginDate = item.FindControl("DeviceContractBeginDate") as HtmlInputText;
                        var dDeviceContractType = item.FindControl("d_DeviceContractType") as HtmlSelect;
                        var dDeviceNature = item.FindControl("d_DeviceNature") as HtmlSelect;
                        var dDeviceAffiliation = item.FindControl("d_DeviceAffiliation") as HtmlSelect;
                        var toDeviceEms = item.FindControl("ToDeviceEMS") as HtmlInputText;
                        var deviceParty = item.FindControl("d_DeviceParty") as HtmlSelect;
                        var deviceCopies = item.FindControl("DeviceCopies") as HtmlInputHidden;
                        var deviceFileNo = item.FindControl("DeviceFileNO") as HtmlInputText;
                        var deviceExpressDate = item.FindControl("DeviceExpressDate") as HtmlInputText;
                        var deviceEms = item.FindControl("DeviceEms") as HtmlInputText;
                        var deviceFinance = item.FindControl("DeviceFinance") as HtmlInputCheckBox;
                        var deviceArchive = item.FindControl("DeviceArchive") as HtmlInputText;
                        var deviceRegionReceive = item.FindControl("DeviceRegionReceive") as HtmlInputCheckBox;
                        var deviceRemark = item.FindControl("DeviceRemark") as HtmlInputText;
                        var tbDeviceNotSignReason = item.FindControl("tb_DeviceNotSignReason") as HtmlInputText;

                        newDeviceContract.DeviceContractSN = AksRequest.GetFormString(deviceContractSn.Name);
                        newDeviceContract.DeviceFixAssetNo = AksRequest.GetFormString(deviceFixAssetNo.Name);
                        newDeviceContract.DeviceContractBeginDate = Utils.StrToDateTime(AksRequest.GetFormString(deviceContractBeginDate.Name));
                        newDeviceContract.DeviceContractType = AksRequest.GetFormString(dDeviceContractType.Name);
                        newDeviceContract.DeviceNature = AksRequest.GetFormString(dDeviceNature.Name);
                        newDeviceContract.DeviceAffiliation = AksRequest.GetFormString(dDeviceAffiliation.Name);
                        newDeviceContract.ToDeviceEms = AksRequest.GetFormString(toDeviceEms.Name);
                        newDeviceContract.DeviceParty = AksRequest.GetFormString(deviceParty.Name);
                        newDeviceContract.DeviceCopies = Utils.StrToInt(AksRequest.GetFormString(deviceCopies.Name), 0);
                        newDeviceContract.DeviceFileNO = AksRequest.GetFormString(deviceFileNo.Name);
                        newDeviceContract.DeviceExpressDate = Utils.StrToDateTime(AksRequest.GetFormString(deviceExpressDate.Name));
                        newDeviceContract.DeviceEms = AksRequest.GetFormString(deviceEms.Name);
                        newDeviceContract.DeviceFinance = AksRequest.GetFormString(deviceFinance.Name).Equals("on");
                        newDeviceContract.DeviceArchive = AksRequest.GetFormString(deviceArchive.Name);
                        newDeviceContract.DeviceRegionReceive = AksRequest.GetFormString(deviceRegionReceive.Name).Equals("on");
                        newDeviceContract.DeviceRemark = AksRequest.GetFormString(deviceRemark.Name);
                        newDeviceContract.DeviceID = deviceContract.DeviceID;
                        newDeviceContract.StoreID = _store.StoreID;
                        newDeviceContract.DeviceNotSignReason = newDeviceContract.DeviceNature == "无法签署" ? AksRequest.GetFormString(tbDeviceNotSignReason.Name) : "";
                    }

                    if (deviceContract.ContractDeviceID == 0)
                    {
                        newDeviceContract.EntityState._Loaded = false;
                        newDeviceContract.EntityState._FieldState.Remove("ContractDeviceID");
                        Storage.Save(Storage.Context3, newDeviceContract);
                    }
                    else
                    {
                        var deviceChangelogs = DataHelper<t_smd_ContractDevice>.GetChangeLogs(deviceContract, newDeviceContract,
                            newDeviceContract.GetChangeFields(), "ContractDeviceID", UserAPI.UserFullName, assID, "ChangeDeviceContract");
                        // ReSharper disable once CoVariantArrayConversion
                        Storage.Save(Storage.Context1, deviceChangelogs.ToArray());
                    }
                }

                //if (key == Constant.PROCESS_TRANSFER)
                //{
                //    var deviceContract = ContractDevices[0];
                //    if (deviceContract.ContractDeviceID != 0)
                //    {
                //        var existingDeviceChangelogs = ChangeLogService.GetLastChangeLogs(TaskAPI).Where(t => t.Category == "ChangeDeviceContract" & t.DataID == deviceContract.ContractDeviceID.ToString(CultureInfo.InvariantCulture)).ToList();
                //        DataHelper<t_smd_ContractDevice>.Reload(deviceContract, existingDeviceChangelogs);
                //    }

                //    var newDeviceContract = (t_smd_ContractDevice)deviceContract.CloneObject();
                //    newDeviceContract.FineAmount = Utils.StrToDecimal(tb_FineAmount.Text.Replace(",", ""), 0);
                //    newDeviceContract.PartyACustomer = tb_PartyACustomer.Text;
                //    newDeviceContract.TransferAmount = Utils.StrToDecimal(tb_TransferAmount.Text.Replace(",", ""), 0);
                //    newDeviceContract.PartyBCustomer = tb_PartyBCustomer.Text;
                //    newDeviceContract.TransferFromStoreSN = uc_store_info2.store == null ? "" : uc_store_info2.store.AuthID;
                //    newDeviceContract.TransferToStoreSN = uc_store_info1.store == null ? "" : uc_store_info1.store.AuthID;
                //    newDeviceContract.TransferContractDate = DateTime.Now;

                //    var deviceChangelogs = DataHelper<t_smd_ContractDevice>.GetChangeLogs(deviceContract, newDeviceContract,
                //            newDeviceContract.GetChangeFields(), "ContractDeviceID", UserAPI.UserFullName, assID, "ChangeDeviceContract");
                //    // ReSharper disable once CoVariantArrayConversion
                //    Storage.Save(Storage.Context1, deviceChangelogs.ToArray());
                //}
            }
            #endregion

        }
        #endregion

        #region 提交按钮事件
        protected void btn_submit_Click(object sender, EventArgs e)
        {
            var returnMsg = string.Empty;
            if (Send(ref returnMsg))
            {
                btn_submit.Visible = false;
                ScriptManager.RegisterStartupScript(this, GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { window.opener.reload(); closeWin(); } });", true);
            }
            else
            {
                returnMsg = returnMsg ?? Resources.Global.C_00_Failed;
                ScriptManager.RegisterStartupScript(this, GetType(), "info_tip", "$.jBox.prompt('" + returnMsg + "','提示', 'info');", true);
            }
        }
        #endregion

        #region 暂存按钮事件

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            var ass = DwzAssessment1.Assessment;
            ass.OpinionText = "暂存";
            Storage.Save(Storage.Context1, ass);
           
            var assID = ass.ID;
            if (ass.ID == null)
            {
                assID = AssessmentService.GetIdsByTaskApi(TaskAPI)[0];
            }
            var storeMasterData = (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).ListFirst<t_StoreMasterData>();
            if (storeMasterData == null)
            {
                storeMasterData = new t_StoreMasterData
                {
                    SubmitDate = DateTime.Now,
                    Creator = TaskAPI.UserName,
                    ApplicationNO = uc_head1.applicationNo,
                    Process = TaskAPI.Process,
                    Incident = TaskAPI.Incident,
                    StoreId = _storeid,

                    AreaName = uc_store_info1.store.Region,
                    ProvinceName = uc_store_info1.store.Province,
                    CityName = uc_store_info1.store.CityName
                };
                Storage.Save(Storage.Context1, storeMasterData);
            }
            SaveChangeLog(assID);
            SaveCancelInfo();
            ScriptManager.RegisterStartupScript(this, GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { window.opener.reload(); closeWin(); } });", true);
        }

        #endregion

        #region DataStoreEditBind
        private void DataStoreEditBind(t_smd_Contract contract)
        {
            if (contract != null) { 
                if (_storeid != 0)
                {
                    l_StoreCopies.Text = @"3";
                }
                ddl_StoreParty.Text = contract.StoreParty;
                tr_StoreNoSign.Style.Add("display", "none");
                if (contract == null || contract.ContractID == 0) return;
                ddl_StoreContractType.SelectedValue = contract.StoreContractType;
                ddl_StoreContractSN.SelectedValue = contract.StoreContractSN;
                tb_StoreContractBeginDate.Text = contract.StoreContractBeginDate == null ? "" : contract.StoreContractBeginDate.Value.ToString("yyyy-MM-dd");

                StoreNature.Text = contract.StoreNature;
                if (contract.StoreNature == "无法签署")
                {
                    tr_StoreNoSign.Style.Add("display", "");
                    tb_StoreNotSignReason.Text = contract.StoreNotSignReason;
                }
                else
                {
                    tr_StoreNoSign.Style.Add("display", "none");
                }
                StoreAffiliation.SelectedValue = contract.StoreAffiliation;
                l_StoreCopies.Text = @"3";
                Remark.Text = contract.Remark;
                tb_StoreContractBeginDate.Text = contract.StoreContractBeginDate == null
                    ? ""
                    : contract.StoreContractBeginDate.Value.ToString("yyyy-MM-dd");
                tb_ToStoreEms.Text = contract.ToStoreEms;
                tb_StoreFileNO.Text = contract.StoreFileNO;
                StoreRegionReceive.Checked = contract.StoreRegionReceive.HasValue && contract.StoreRegionReceive.Value;
                StoreFinance.Checked = contract.StoreFinance == true;
                Remark.Text = contract.Remark;
                tb_AwardContractBeginDate.Text = contract.AwardContractBeginDate == null ? "" : contract.AwardContractBeginDate.Value.ToString("yyyy-MM-dd");
                tb_AwardContractEndDate.Text = contract.AwardContractEndDate == null ? "" : contract.AwardContractEndDate.Value.ToString("yyyy-MM-dd");
                tb_StoreFileNO.Text = contract.StoreFileNO;
                tb_ToStoreEms.Text = contract.ToStoreEms;
                StoreExpressDate.Text = contract.StoreExpressDate == null ? DateTime.Now.ToString("yyyy-MM-dd") : contract.StoreExpressDate.Value.ToString("yyyy-MM-dd");
                StoreEms.Text = contract.StoreEms;
                StoreArchive.Text = contract.StoreArchive;
            }
        }
        #endregion

        #region DataStoreViewBind
        private void DataStoreViewBind(t_smd_Contract contract)
        {
            if (contract != null)
            {
                l_StoreParty.Text = contract.StoreParty;
                l_StoreContractType.Text = contract.StoreContractType;
                l_StoreContractBeginDate.Text = contract.StoreContractBeginDate == null ? "" : contract.StoreContractBeginDate.Value.ToString("yyyy-MM-dd");
                l_AwardContractBeginDate.Text = contract.AwardContractBeginDate == null ? "" : contract.AwardContractBeginDate.Value.ToString("yyyy-MM-dd");
                l_AwardContractEndDate.Text = contract.AwardContractEndDate == null ? "" : contract.AwardContractEndDate.Value.ToString("yyyy-MM-dd");
                l_StoreContractSN.Text = contract.StoreContractSN;
                l_RenewContractBeginDate.Text = contract.RenewContractBeginDate == null ? "" : contract.RenewContractBeginDate.Value.ToString("yyyy-MM-dd");
                l_RenewContractEndDate.Text = contract.RenewContractEndDate == null ? "" : contract.RenewContractEndDate.Value.ToString("yyyy-MM-dd");

                if (contract.StoreNature == "无法签署")
                {
                    tr_StoreNoSign.Style.Add("display", "");
                    l_StoreNotSignReason.Text = contract.StoreNotSignReason;
                }
                else
                {
                    tr_StoreNoSign.Style.Add("display", "none");
                }

                l_StoreNature.Text = contract.StoreNature;
                l_StoreAffiliation.Text = contract.StoreAffiliation;
                l_StoreParty.Text = contract.StoreParty;
                l_StoreCopies.Text = contract.StoreCopies.ToString();
                if (!string.IsNullOrEmpty(StoreExpressDate.Text))
                {
                    l_StoreExpressDate.Text = contract.StoreExpressDate == null
                        ? ""
                        : contract.StoreExpressDate.Value.ToString("yyyy-MM-dd");
                }
                l_StoreEms.Text = contract.StoreEms;
                l_StoreFinance.Text = contract.StoreFinance.HasValue ? contract.StoreFinance.Value ? "是" : "否" : "否";
                l_StoreArchive.Text = contract.StoreArchive;
                l_Remark.Text = contract.Remark;
                l_StoreFileNO.Text = contract.StoreFileNO;
                l_ToStoreEms.Text = contract.ToStoreEms;
                StoreRegionReceive.Checked = contract.StoreRegionReceive.HasValue && contract.StoreRegionReceive.Value;
            }
        }
        #endregion

        #region DataStoreCancelBind
        //private void DataStoreCancelViewBind(t_smd_Contract_Cancel contract)
        //{
        //    l_StoreCancelParty.Text = contract.StoreCancelParty;
        //    l_StoreCancelContractType.Text = contract.StoreCancelContractType;
        //    l_StoreCancelContractBeginDate.Text = contract.StoreCancelContractBeginDate == null ? "" : contract.StoreCancelContractBeginDate.Value.ToString("yyyy-MM-dd");
        //    if (contract.StoreCancelNature == "无法签署")
        //    {
        //        tr_StoreNoSign.Style.Add("display", "");
        //        l_StoreNotSignReason.Text = contract.StoreCancelNotSignReason;
        //    }
        //    else
        //    {
        //        tr_StoreNoSign.Style.Add("display", "none");
        //    }

        //    l_StoreCancelNature.Text = contract.StoreCancelNature;
        //    l_StoreCancelAffiliation.Text = contract.StoreCancelAffiliation;
        //    l_StoreCancelCopies.Text = contract.StoreCancelCopies.ToString();
        //    l_StoreCancelExpressDate.Text = contract.StoreCancelExpressDate == null
        //        ? ""
        //        : contract.StoreCancelExpressDate.Value.ToString("yyyy-MM-dd");
        //    l_StoreCancelEms.Text = contract.StoreCancelEms;
        //    l_StoreCancelFinance.Text = contract.StoreCancelFinance.HasValue ? contract.StoreCancelFinance.Value ? "是" : "否" : "否";
        //    l_StoreCancelArchive.Text = contract.StoreCancelArchive;
        //    l_CancelRemark.Text = contract.CancelRemark;
        //    l_StoreCancelFileNO.Text = contract.StoreCancelFileNO;
        //    l_ToStoreCancelEms.Text = contract.ToStoreCancelEms;
        //    l_StoreCancelRegionReceive.Text = contract.StoreCancelRegionReceive.HasValue ? contract.StoreCancelRegionReceive.Value ? "是" : "否" : "否";
            
        //}
        #endregion

        #region 设备循环显示
        protected void rpt_deviceContract_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var configService = new ConfigService();
            if (e.Item.ItemType != ListItemType.AlternatingItem && e.Item.ItemType != ListItemType.Item) return;

            #region 绑定设备合同类型
            var dDeviceContractType = e.Item.FindControl("d_DeviceContractType") as HtmlSelect;
            var hDeviceContractType = e.Item.FindControl("h_DeviceContractType") as HtmlInputHidden;
            if (dDeviceContractType != null && hDeviceContractType != null)
            {
                dDeviceContractType.DataSource = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_SBHTLX') order by seq").Tables[0];
                dDeviceContractType.DataTextField = "name";
                dDeviceContractType.DataValueField = "name";
                dDeviceContractType.DataBind();
                dDeviceContractType.Value = hDeviceContractType.Value;
            }
            #endregion

            #region 绑定设备合同性质
            var dDeviceNature = e.Item.FindControl("d_DeviceNature") as HtmlSelect;
            var hDeviceNature = e.Item.FindControl("h_DeviceNature") as HtmlInputHidden;
            if (dDeviceNature != null && hDeviceNature != null)
            {
                dDeviceNature.DataSource = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_HTXZ') order by seq").Tables[0];
                dDeviceNature.DataTextField = "name";
                dDeviceNature.DataValueField = "name";
                dDeviceNature.DataBind();
                dDeviceNature.Value = hDeviceNature.Value;
            }
            #endregion

            #region 绑定合同归属
            var dDeviceAffiliation = e.Item.FindControl("d_DeviceAffiliation") as HtmlSelect;
            var hDeviceAffiliation = e.Item.FindControl("h_DeviceAffiliation") as HtmlInputHidden;
            if (dDeviceAffiliation != null && hDeviceAffiliation != null)
            {
                dDeviceAffiliation.DataSource = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_HTGS') order by seq").Tables[0];
                dDeviceAffiliation.DataTextField = "name";
                dDeviceAffiliation.DataValueField = "name";
                dDeviceAffiliation.DataBind();
                dDeviceAffiliation.Value = hDeviceAffiliation.Value;
                
            }
            #endregion

            #region 绑定设备合同甲方

            var dDeviceParty = e.Item.FindControl("d_DeviceParty") as HtmlSelect;
            var hDeviceParty = e.Item.FindControl("h_DeviceContractSN") as HtmlInputHidden;
            if (dDeviceParty != null && hDeviceParty != null)
            {
                dDeviceParty.DataSource = configService.GetList("ParentId = (select configid from t_smd_Config where code='HTJF') order by seq").Tables[0];
                dDeviceParty.DataTextField = "name";
                dDeviceParty.DataValueField = "name";
                dDeviceParty.DataBind();
                dDeviceParty.Value = hDeviceParty.Value;
                
            }

            #endregion

            #region 绑定设备合同版本号

            var dDeviceContractSN = e.Item.FindControl("d_DeviceContractSN") as HtmlSelect;
            var hDeviceContractSN = e.Item.FindControl("h_DeviceContractSN") as HtmlInputHidden;
            if (dDeviceContractSN != null && hDeviceContractSN != null)
            {
                dDeviceContractSN.DataSource = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_SBBBH') order by seq").Tables[0];
                dDeviceContractSN.DataTextField = "name";
                dDeviceContractSN.DataValueField = "name";
                dDeviceContractSN.DataBind();
                dDeviceContractSN.Value = hDeviceContractSN.Value;
                
            }

            #endregion

            var deviceContractSn = e.Item.FindControl("d_DeviceContractSN") as HtmlSelect;
            var deviceFixAssetNo = e.Item.FindControl("DeviceFixAssetNo") as HtmlInputText;
            var deviceContractBeginDate = e.Item.FindControl("DeviceContractBeginDate") as HtmlInputText;
            var toDeviceEMS = e.Item.FindControl("ToDeviceEMS") as HtmlInputText;
            var deviceParty = e.Item.FindControl("d_DeviceParty") as HtmlSelect;
            var deviceCopies = e.Item.FindControl("DeviceCopies") as HtmlInputHidden;
            var deviceFileNo = e.Item.FindControl("DeviceFileNO") as HtmlInputText;
            var deviceExpressDate = e.Item.FindControl("DeviceExpressDate") as HtmlInputText;
            var deviceEms = e.Item.FindControl("DeviceEms") as HtmlInputText;
            var deviceFinance = e.Item.FindControl("DeviceFinance") as HtmlInputCheckBox;
            var hDeviceFinance = e.Item.FindControl("h_DeviceFinance") as HtmlInputHidden;
            var trDeviceNoSign = e.Item.FindControl("tr_DeviceNoSign") as HtmlTableRow;

            if (hDeviceFinance.Value == "True")
                deviceFinance.Checked = true;

            var deviceArchive = e.Item.FindControl("DeviceArchive") as HtmlInputText;
            var deviceRegionReceive = e.Item.FindControl("DeviceRegionReceive") as HtmlInputCheckBox;
            var hDeviceRegionReceive = e.Item.FindControl("h_DeviceRegionReceive") as HtmlInputHidden;
            if (hDeviceRegionReceive.Value == "True")
                deviceRegionReceive.Checked = true;

            var deviceRemark = e.Item.FindControl("DeviceRemark") as HtmlInputText;
            var deviceNotSignReason = e.Item.FindControl("tb_DeviceNotSignReason") as HtmlInputText;

            var lDeviceContractType = e.Item.FindControl("l_DeviceContractType") as Literal;
            var lDeviceNature = e.Item.FindControl("l_DeviceNature") as Literal;
            var lDeviceAffiliation = e.Item.FindControl("l_DeviceAffiliation") as Literal;
            var lDeviceFixAssetNo = e.Item.FindControl("l_DeviceFixAssetNo") as Literal;
            var lDeviceContractBeginDate = e.Item.FindControl("l_DeviceContractBeginDate") as Literal;
            var lToDeviceEMS = e.Item.FindControl("l_ToDeviceEMS") as Literal;
            var lDeviceFileNo = e.Item.FindControl("l_DeviceFileNO") as Literal;
            var lDeviceExpressDate = e.Item.FindControl("l_DeviceExpressDate") as Literal;
            var lDeviceEms = e.Item.FindControl("l_DeviceEms") as Literal;
            var lDeviceFinance = e.Item.FindControl("l_DeviceFinance") as Literal;
            var lDeviceArchive = e.Item.FindControl("l_DeviceArchive") as Literal;
            var lDeviceRegionReceive = e.Item.FindControl("l_DeviceRegionReceive") as Literal;
            var lDeviceRemark = e.Item.FindControl("l_DeviceRemark") as Literal;
            var lDeviceNotSignReason = e.Item.FindControl("l_DeviceNotSignReason") as Literal;
            var lDeviceContractSN = e.Item.FindControl("l_DeviceContractSN") as Literal;
            var DeviceID = e.Item.FindControl("DeviceID") as HtmlInputHidden;
            var lDeviceParty = e.Item.FindControl("l_DeviceParty") as Literal;

            if (dDeviceNature.Value != "无法签署")
            {
                trDeviceNoSign.Style.Add("display", "none");

            }
            else
            {
                trDeviceNoSign.Style.Add("display", "");
                deviceNotSignReason.Attributes.Add("datatype", "*");
            }


            if (TaskAPI.Step == "DMO Commit" || AksRequest.GetString("readonly") == "1")
            {
                deviceContractSn.Visible = false;
                deviceFixAssetNo.Visible = false;
                deviceContractBeginDate.Visible = false;
                toDeviceEMS.Visible = false;
                deviceParty.Visible = false;
                deviceCopies.Visible = false;
                deviceFileNo.Visible = false;
                deviceExpressDate.Visible = false;
                deviceEms.Visible = false;
                deviceFinance.Visible = false;
                dDeviceContractType.Visible = false;
                dDeviceNature.Visible = false;
                dDeviceAffiliation.Visible = false;
                deviceRemark.Visible = false;
                deviceNotSignReason.Visible = false;
                deviceArchive.Visible = false;
                deviceRegionReceive.Visible = false;
            }
            else
            {
                lDeviceFixAssetNo.Visible = false;
                lDeviceContractBeginDate.Visible = false;
                lToDeviceEMS.Visible = false;
                lDeviceFileNo.Visible = false;
                lDeviceExpressDate.Visible = false;
                lDeviceEms.Visible = false;
                lDeviceFinance.Visible = false;
                lDeviceContractType.Visible = false;
                lDeviceNature.Visible = false;
                lDeviceAffiliation.Visible = false;
                lDeviceRemark.Visible = false;
                lDeviceArchive.Visible = false;
                lDeviceRegionReceive.Visible = false;
                lDeviceNotSignReason.Visible = false;
                lDeviceContractSN.Visible = false;
                lDeviceParty.Visible = false;
            }
            //var deviceCancel = ContractDeviceService.getCotractDeviceCancelByDeviceID(Utils.StrToInt(DeviceID.Value, 0));
            //if (deviceCancel != null)
            //{
            //    var lDeviceCancelContractType = e.Item.FindControl("l_DeviceCancelContractType") as Literal;
            //    var lDeviceCancelNature = e.Item.FindControl("l_DeviceCancelNature") as Literal;
            //    var lDeviceCancelAffiliation = e.Item.FindControl("l_DeviceCancelAffiliation") as Literal;
            //    var lDeviceCancelFixAssetNo = e.Item.FindControl("l_DeviceCancelFixAssetNo") as Literal;
            //    var lDeviceCancelContractBeginDate = e.Item.FindControl("l_DeviceCancelContractBeginDate") as Literal;
            //    var lToDeviceCancelEMS = e.Item.FindControl("l_ToDeviceCancelEMS") as Literal;
            //    var lDeviceCancelFileNo = e.Item.FindControl("l_DeviceCancelFileNO") as Literal;
            //    var lDeviceCancelExpressDate = e.Item.FindControl("l_DeviceCancelExpressDate") as Literal;
            //    var lDeviceCancelEms = e.Item.FindControl("l_DeviceCancelEms") as Literal;
            //    var lDeviceCancelFinance = e.Item.FindControl("l_DeviceCancelFinance") as Literal;
            //    var lDeviceCancelArchive = e.Item.FindControl("l_DeviceCancelArchive") as Literal;
            //    var lDeviceCancelRegionReceive = e.Item.FindControl("l_DeviceCancelRegionReceive") as Literal;
            //    var lDeviceCancelRemark = e.Item.FindControl("l_DeviceCancelRemark") as Literal;
            //    var lDeviceCancelNotSignReason = e.Item.FindControl("l_DeviceCancelNotSignReason") as Literal;

            //    lDeviceCancelContractType.Text = deviceCancel.DeviceCancelContractType;
            //    lDeviceCancelNature.Text = deviceCancel.DeviceCancelNature;
            //    lDeviceCancelAffiliation.Text = deviceCancel.DeviceCancelAffiliation;
            //    lDeviceCancelFixAssetNo.Text = deviceCancel.DeviceCancelFixAssetNo;
            //    lDeviceCancelContractBeginDate.Text = deviceCancel.DeviceCancelContractBeginDate.HasValue
            //        ? deviceCancel.DeviceCancelContractBeginDate.Value.ToString("yyyy-MM-dd"): "";
            //    lToDeviceCancelEMS.Text = deviceCancel.ToDeviceCancelEms;
            //    lDeviceCancelFileNo.Text = deviceCancel.DeviceCancelFileNO;
            //    lDeviceCancelExpressDate.Text = deviceCancel.DeviceCancelExpressDate.HasValue
            //        ? deviceCancel.DeviceCancelExpressDate.Value.ToString("yyyy-MM-dd"):"";
            //    lDeviceCancelEms.Text = deviceCancel.DeviceCancelEms;
            //    lDeviceCancelFinance.Text = deviceCancel.DeviceCancelFinance.HasValue?deviceCancel.DeviceCancelFinance.Value?"是":"否":"否";
            //    lDeviceCancelArchive.Text = deviceCancel.DeviceCancelArchive;
            //    lDeviceCancelRegionReceive.Text = deviceCancel.DeviceCancelRegionReceive.HasValue?deviceCancel.DeviceCancelRegionReceive.Value?"是":"否":"否";
            //    lDeviceCancelRemark.Text = deviceCancel.DeviceCancelRemark;
            //    lDeviceCancelNotSignReason.Text = deviceCancel.DeviceCancelNotSignReason;
            //}
            //else
            //{
            //    var tbody = e.Item.FindControl("tb_DeviceCancel") as HtmlGenericControl;
            //    tbody.Visible = false;
            //}
        }
        #endregion

        #region 只读表单
        private bool ReadOnly(t_smd_ContractDevice contractDevice)
        {
            
            if (AksRequest.GetString("readonly") == "1")
            {
                // 只读表单，释放抢占
                OpenTasksInstance.OpenTasks.SetTaskClose(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);

                ShowCancelInfo(false);
                assessment.Visible = true;
                btn_submit.Visible = false;
                AjaxUpload1.AllowUpload = false;
                AjaxUpload1.AllowDelete = false;
                DwzAssessment1.Visible = false;
                uc_store_info1.IsCanEditAuthID = false;
                //cb_storeContract.Visible = false;
                cb_deviceContract.Visible = false;


                var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                if (storeMasterData == null)
                {
                    JsTip("该流程还没有提交过，没有任何数据！");
                    return true;
                }
                uc_change_field1.AssessmentIDs = AssessmentService.GetIdsByTaskApi(TaskAPI);
                if (TaskAPI.GetVariableBySingleValue("AutoBusinessKey") == Constant.PROCESS_TRANSFER)
                {
                    //ViewTransferData(contractDevice, false);
                }

                if (storeMasterData.StoreId != null)
                {
                    uc_store_info1.store = StoreService.GetSmdStoreById(storeMasterData.StoreId.Value);
                    uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                    uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");
                    if (storeMasterData.SubmitDate != null)
                        uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                    DwzAssessment1.Category = null;

                    if (_needSaveStore)
                    {
                        var contract = (t_smd_Contract._StoreID == storeMasterData.StoreId.Value).ListFirst<t_smd_Contract>(Storage.Context3) ??
                                       new t_smd_Contract { StoreID = storeMasterData.StoreId.Value };
                        contract = DataHelper<t_smd_Contract>.Reload(contract, _contractLogs);
                        ViewStoreData(contract, false);
                    }
                }

                hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                hl_ExportPdf.Visible = true;
                btn_print.Visible = true;

                return true;
            }
            return false;
        }
        #endregion

        #region 展示终止合同信息

        protected void ShowCancelInfo(bool canEdit)
        {
            if (_needDeviceCancel)
            {
                var deviceCancelContract = ContractDeviceService.getCotractDeviceCancelByDeviceID(_device.DeviceID);
                if (canEdit)
                {
                    //DeviceCancelContractSN.Text = deviceCancelContract.DeviceCancelContractSN;
                    DeviceCancelContractSN.Items.Add(new ListItem("Contract-TT-1701A", "Contract-TT-1701A"));
                    DeviceCancelContractSN.Items.Add(new ListItem("1306A", "1306A"));
                    DeviceCancelContractSN.SelectedValue = deviceCancelContract.DeviceCancelContractSN;
                    DeviceCancelFixAssetNo.Text = deviceCancelContract.DeviceCancelFixAssetNo;
           
                    DeviceCancelContractBeginDate.Value = deviceCancelContract.DeviceCancelContractBeginDate.HasValue
                        ? deviceCancelContract.DeviceCancelContractBeginDate.Value.ToString("yyyy-MM-dd")
                        : "";
                    DeviceCancelContractType.Text = deviceCancelContract.DeviceCancelContractType;
                    s_DeviceCancelNature.SelectedValue = deviceCancelContract.DeviceCancelNature;
                    s_DeviceCancelAffiliation.SelectedValue = deviceCancelContract.DeviceCancelAffiliation;
                    ToDeviceCancelEms.Value = deviceCancelContract.ToDeviceCancelEms;
                    DeviceCancelParty.SelectedValue = deviceCancelContract.DeviceCancelParty;
                    DeviceCopies.Value = "3";
                    DeviceCancelFileNO.Value = deviceCancelContract.DeviceCancelFileNO;
                    DeviceCancelExpressDate.Value = deviceCancelContract.DeviceCancelExpressDate.HasValue
                        ? deviceCancelContract.DeviceCancelExpressDate.Value.ToString("yyyy-MM-dd")
                        : "";
                    DeviceCancelEms.Value = deviceCancelContract.DeviceCancelEms;
                    if (deviceCancelContract.DeviceCancelNature == "无法签署")
                    {
                        tr_DeviceCancelNoSign.Style.Add("display", "");
                        tb_DeviceCancelNotSignReason.Text = deviceCancelContract.DeviceCancelNotSignReason;
                    }
                    else
                    {
                        tr_DeviceCancelNoSign.Style.Add("display", "none");
                    }
                    tb_DeviceCancelNotSignReason.Text = deviceCancelContract.DeviceCancelNotSignReason;
                    DeviceCancelFinance.Checked = deviceCancelContract.DeviceCancelFinance.HasValue &&
                                                  deviceCancelContract.DeviceCancelFinance.Value;
                    DeviceCancelArchive.Value = deviceCancelContract.DeviceCancelArchive;
                    DeviceCancelRegionReceive.Checked = deviceCancelContract.DeviceCancelRegionReceive.HasValue &&
                                                        deviceCancelContract.DeviceCancelRegionReceive.Value;
                    DeviceCancelRemark.Value = deviceCancelContract.DeviceCancelRemark;
                    if (TaskAPI.GetVariableBySingleValue("AutoBusinessKey").Equals(Constant.PROCESS_TRANSFER))
                    {
                        tb_PartyACustomer.Text = deviceCancelContract.PartyACustomer;
                        tb_PartyBCustomer.Text = deviceCancelContract.PartyBCustomer;
                        tb_FineAmount.Text = deviceCancelContract.FineAmount.ToString("N");
                        tb_TransferAmount.Text = deviceCancelContract.TransferAmount.ToString("N"); ;
                    }
                }
                else
                {
                    #region 隐藏tb
                    if (TaskAPI.GetVariableBySingleValue("AutoBusinessKey").Equals(Constant.PROCESS_TRANSFER))
                    {
                        tb_PartyACustomer.Visible = false;
                        tb_PartyBCustomer.Visible = false;
                        tb_FineAmount.Visible = false;
                        tb_TransferAmount.Visible = false;
                        l_PartyACustomer.Text = deviceCancelContract.PartyACustomer;
                        l_PartyBCustomer.Text = deviceCancelContract.PartyBCustomer;
                        l_FineAmount.Text = deviceCancelContract.FineAmount.ToString("N");
                        l_TransferAmount.Text = deviceCancelContract.TransferAmount.ToString("N");
                    }
                    //DeviceCancelContractSN.Visible = false;
                    DeviceCancelContractSN.Visible = false;
                    DeviceCancelFixAssetNo.Visible = false;
                    DeviceCancelContractBeginDate.Visible = false;
                    //DeviceCancelContractType.Visible = false;
                    s_DeviceCancelNature.Visible = false;
                    s_DeviceCancelAffiliation.Visible = false;
                    ToDeviceCancelEms.Visible = false;
                    DeviceCancelParty.Visible = false;
                    DeviceCopies.Value = "3";
                    DeviceCancelFileNO.Visible = false;
                    DeviceCancelExpressDate.Visible = false;
                    DeviceCancelEms.Visible = false;
                    tb_DeviceCancelNotSignReason.Visible = false;
                    DeviceCancelFinance.Checked = deviceCancelContract.DeviceCancelFinance.HasValue &&
                                                  deviceCancelContract.DeviceCancelFinance.Value;
                    DeviceCancelFinance.Disabled = true;
                    DeviceCancelArchive.Visible = false;
                    DeviceCancelRegionReceive.Checked = deviceCancelContract.DeviceCancelRegionReceive.HasValue &&
                                                        deviceCancelContract.DeviceCancelRegionReceive.Value;
                    DeviceCancelRegionReceive.Disabled = true;
                    DeviceCancelRemark.Visible = false;
                    #endregion
                    #region 给Letial赋值
                    if (deviceCancelContract.DeviceCancelNature == "无法签署")
                    {
                        tr_DeviceCancelNoSign.Style.Add("display", "");
                        l_DeviceCancelNotSignReason.Text = deviceCancelContract.DeviceCancelNotSignReason;
                    }
                    else
                    {
                        tr_DeviceCancelNoSign.Style.Add("display", "none");
                    }
                    //l_DeviceCancelContractSN.Text = deviceCancelContract.DeviceCancelContractSN;
                    l_DevieCancelContractSN.Text = deviceCancelContract.DeviceCancelContractSN;
                    l_DeviceCancelFixAssetNo.Text = deviceCancelContract.DeviceCancelFixAssetNo;
                    l_DeviceCancelContractBeginDate.Text = deviceCancelContract.DeviceCancelContractBeginDate.HasValue
                        ? deviceCancelContract.DeviceCancelContractBeginDate.Value.ToString("yyyy-MM-dd")
                        : "";
                    DeviceCancelContractType.Text = deviceCancelContract.DeviceCancelContractType;
                    l_DeviceCancelNature.Text = deviceCancelContract.DeviceCancelNature;
                    l_DeviceCancelAffiliation.Text = deviceCancelContract.DeviceCancelAffiliation;
                    l_ToDeviceCancelEms.Text = deviceCancelContract.ToDeviceCancelEms;
                    l_DeviceCancelParty.Text = deviceCancelContract.DeviceCancelParty;
                    DeviceCopies.Value = "3";
                    l_DeviceCancelFileNO.Text = deviceCancelContract.DeviceCancelFileNO;
                    l_DeviceCancelExpressDate.Text = deviceCancelContract.DeviceCancelExpressDate.HasValue
                        ? deviceCancelContract.DeviceCancelExpressDate.Value.ToString("yyyy-MM-dd")
                        : "";
                    l_DeviceCancelEms.Text = deviceCancelContract.DeviceCancelEms;
                    DeviceCancelFinance.Checked = deviceCancelContract.DeviceCancelFinance.HasValue &&
                                                  deviceCancelContract.DeviceCancelFinance.Value;
                    l_StoreNotSignReason.Text = deviceCancelContract.DeviceCancelNotSignReason;
                    DeviceCancelFinance.Disabled = true;
                    l_DeviceCancelArchive.Text = deviceCancelContract.DeviceCancelArchive;
                    DeviceCancelRegionReceive.Checked = deviceCancelContract.DeviceCancelRegionReceive.HasValue &&
                                                        deviceCancelContract.DeviceCancelRegionReceive.Value;
                    DeviceCancelRegionReceive.Disabled = true;
                    l_DeviceCancelRemark.Text = deviceCancelContract.DeviceCancelRemark;
                    #endregion
                }

            }
            #region 隐藏门店终止合同 2016-11-04
            //if (_needStoreCancel)
            //{
            //    var storeCancelContract = ContractService.getCotractCancelByDeviceID(_storeid);
            //    if (canEdit)
            //    {
            //        if (storeCancelContract.StoreCancelNature == "无法签署")
            //        {
            //            tr_StoreCancelNoSign.Style.Add("display", "");
            //            tb_StoreCancelNotSignReason.Text = storeCancelContract.StoreCancelNotSignReason;
            //        }
            //        else
            //        {
            //            tr_StoreCancelNoSign.Style.Add("display", "none");
            //        }
            //        //l_StoreCancelContractSN.Text = storeCancelContract.StoreCancelContractSN;
            //        StoreCancelContractType.Text = storeCancelContract.StoreCancelContractType;
            //        StoreCancelContractBeginDate.Value = storeCancelContract.StoreCancelContractBeginDate.HasValue
            //            ? storeCancelContract.StoreCancelContractBeginDate.Value.ToString("yyyy-MM-dd")
            //            : "";
            //        ddl_StoreCancelNature.SelectedValue = storeCancelContract.StoreCancelNature;
            //        ddl_StoreCancelAffiliation.SelectedValue = storeCancelContract.StoreCancelAffiliation;
            //        ToStoreCancelEms.Text = storeCancelContract.ToStoreCancelEms;
            //        StoreCancelParty.SelectedValue = storeCancelContract.StoreCancelParty;
            //        StoreCancelCopies.Value = "3";
            //        tb_StoreCancelNotSignReason.Text = storeCancelContract.StoreCancelNotSignReason;
            //        StoreCancelFileNO.Value = storeCancelContract.StoreCancelFileNO;
            //        StoreCancelExpressDate.Value = storeCancelContract.StoreCancelExpressDate.HasValue
            //            ? storeCancelContract.StoreCancelExpressDate.Value.ToString("yyyy-MM-dd")
            //            : "";
            //        StoreCancelEms.Value = storeCancelContract.StoreCancelEms;
            //        StoreCancelFinance.Checked = storeCancelContract.StoreCancelFinance.HasValue &&
            //                                     storeCancelContract.StoreCancelFinance.Value;
            //        StoreCancelArchive.Value = storeCancelContract.StoreCancelAffiliation;
            //        StoreCancelRegionReceive.Checked = storeCancelContract.StoreCancelRegionReceive.HasValue &&
            //                                           storeCancelContract.StoreCancelRegionReceive.Value;
            //        CancelRemark.Value = storeCancelContract.CancelRemark;
            //    }
            //    else
            //    {
            //        #region 隐藏tb
            //        //ddl_StoreCancelContractSN.Visible = false;
                    
            //        StoreCancelContractBeginDate.Visible = false;
            //        ddl_StoreCancelNature.Visible = false;
            //        ddl_StoreCancelAffiliation.Visible = false;
            //        ToStoreCancelEms.Visible = false;
            //        StoreCancelParty.Visible = false;
            //        StoreCancelCopies.Value = "3";
            //        StoreCancelFileNO.Visible = false;
            //        StoreCancelExpressDate.Visible = false;
            //        StoreCancelEms.Visible = false;
            //        tb_StoreCancelNotSignReason.Visible = false;
            //        StoreCancelFinance.Checked = storeCancelContract.StoreCancelFinance.HasValue &&
            //                                     storeCancelContract.StoreCancelFinance.Value;
            //        StoreCancelFinance.Disabled = true;
            //        StoreCancelArchive.Visible = false;
            //        StoreCancelRegionReceive.Checked = storeCancelContract.StoreCancelRegionReceive.HasValue &&
            //                                           storeCancelContract.StoreCancelRegionReceive.Value;
            //        StoreCancelRegionReceive.Disabled = true;
            //        CancelRemark.Visible = false;
            //        #endregion

            //        #region 给literal赋值
            //        if (storeCancelContract.StoreCancelNature == "无法签署")
            //        {
            //            tr_StoreCancelNoSign.Style.Add("display", "");
            //            l_StoreCancelNotSignReason.Text = storeCancelContract.StoreCancelNotSignReason;
            //        }
            //        else
            //        {
            //            tr_StoreCancelNoSign.Style.Add("display", "none");
            //        }
            //        //l_StoreCancelContractSN.Text = storeCancelContract.StoreCancelContractSN;
            //        StoreCancelContractType.Text = storeCancelContract.StoreCancelContractType;
            //        l_StoreCancelContractBeginDate.Text = storeCancelContract.StoreCancelContractBeginDate.HasValue
            //            ? storeCancelContract.StoreCancelContractBeginDate.Value.ToString("yyyy-MM-dd")
            //            : "";
            //        l_StoreCancelNature.Text = storeCancelContract.StoreCancelNature;
            //        l_StoreCancelAffiliation.Text = storeCancelContract.StoreCancelAffiliation;
            //        l_ToStoreCancelEms.Text = storeCancelContract.ToStoreCancelEms;
            //        l_StoreCancelParty.Text = storeCancelContract.StoreCancelParty;
            //        StoreCancelCopies.Value = "3";
            //        l_StoreCancelFileNO.Text = storeCancelContract.StoreCancelFileNO;
            //        l_StoreCancelExpressDate.Text = storeCancelContract.StoreCancelExpressDate.HasValue
            //            ? storeCancelContract.StoreCancelExpressDate.Value.ToString("yyyy-MM-dd")
            //            : "";
            //        l_StoreNotSignReason.Text = storeCancelContract.StoreCancelNotSignReason;
            //        l_StoreCancelEms.Text = storeCancelContract.StoreCancelEms;
            //        StoreCancelFinance.Checked = storeCancelContract.StoreCancelFinance.HasValue &&
            //                                     storeCancelContract.StoreCancelFinance.Value;
            //        l_StoreCancelArchive.Text = storeCancelContract.StoreCancelAffiliation;
            //        StoreCancelRegionReceive.Checked = storeCancelContract.StoreCancelRegionReceive.HasValue &&
            //                                           storeCancelContract.StoreCancelRegionReceive.Value;
            //        l_CancelRemark.Text = storeCancelContract.CancelRemark;
            //        #endregion
                    
            //    }

            //}
            #endregion
        }

        #endregion

        #region 保存终止信息

        protected void SaveCancelInfo()
        {
            if (_needDeviceCancel)
            {

                var deviceCancelContract = ContractDeviceService.getCotractDeviceCancelByDeviceID(_device.DeviceID);
                deviceCancelContract.DeviceCancelContractSN = DeviceCancelContractSN.SelectedValue; //"1306A";
                deviceCancelContract.DeviceCancelFixAssetNo = DeviceCancelFixAssetNo.Text;
                deviceCancelContract.DeviceCancelContractBeginDate = Utils.StrToDateTime(DeviceCancelContractBeginDate.Value);

                //20161230 update
                if (deviceCancelContract.DeviceCancelContractSN == "1306A")
                {
                    deviceCancelContract.DeviceCancelContractType = "合同终止及三方转移合同";
                }
                else if (deviceCancelContract.DeviceCancelContractSN == "Contract-TT-1701A")
                {
                    deviceCancelContract.DeviceCancelContractType = "设备终止投放及三方转移协议";
                }

               
         
                deviceCancelContract.DeviceCancelNature = s_DeviceCancelNature.SelectedValue;
                deviceCancelContract.DeviceCancelAffiliation = s_DeviceCancelAffiliation.SelectedValue;
                deviceCancelContract.ToDeviceCancelEms = ToDeviceCancelEms.Value;
                deviceCancelContract.DeviceCancelParty = DeviceCancelParty.SelectedValue;
                deviceCancelContract.DeviceCancelCopies = 3;
                deviceCancelContract.DeviceCancelFileNO = DeviceCancelFileNO.Value;
                deviceCancelContract.DeviceCancelExpressDate = Utils.StrToDateTime(DeviceCancelExpressDate.Value);
                deviceCancelContract.DeviceCancelEms = DeviceCancelEms.Value;
                deviceCancelContract.DeviceCancelFinance = DeviceCancelFinance.Checked;
                deviceCancelContract.DeviceCancelArchive = DeviceCancelArchive.Value;
                deviceCancelContract.DeviceCancelRegionReceive = DeviceCancelRegionReceive.Checked;
                deviceCancelContract.DeviceCancelRemark = DeviceCancelRemark.Value;
                deviceCancelContract.DeviceCancelNotSignReason = tb_DeviceCancelNotSignReason.Text;
                if (TaskAPI.GetVariableBySingleValue("AutoBusinessKey").Equals(Constant.PROCESS_TRANSFER))
                {
                    deviceCancelContract.PartyACustomer = tb_PartyACustomer.Text;
                    deviceCancelContract.PartyBCustomer = tb_PartyBCustomer.Text;
                    deviceCancelContract.FineAmount = Utils.StrToDecimal(tb_FineAmount.Text.Replace(",", ""), 0);
                    deviceCancelContract.TransferAmount = Utils.StrToDecimal(tb_TransferAmount.Text.Replace(",", ""), 0);
                }
                Storage.Save(Storage.Context3, deviceCancelContract);

            }

            #region 门店终止合同 2016-11-04
                //if (_needStoreCancel)
                //    {
                //      var storeCancelContract = ContractService.getCotractCancelByDeviceID(_storeid);
                //        storeCancelContract.StoreCancelContractSN = "1306A";
                //        storeCancelContract.StoreCancelContractType = StoreCancelContractType.Text;
                //        storeCancelContract.StoreCancelContractBeginDate = Utils.StrToDateTime(StoreCancelContractBeginDate.Value);
                //        storeCancelContract.StoreCancelNature = ddl_StoreCancelNature.SelectedValue;
                //        storeCancelContract.StoreCancelAffiliation = ddl_StoreCancelAffiliation.SelectedValue;
                //        storeCancelContract.ToStoreCancelEms = ToStoreCancelEms.Text;
                //        storeCancelContract.StoreCancelParty = StoreCancelParty.SelectedValue;
                //        storeCancelContract.StoreCancelCopies = 3;
                //        storeCancelContract.StoreCancelFileNO = StoreCancelFileNO.Value;
                //        storeCancelContract.StoreCancelExpressDate = Utils.StrToDateTime(StoreCancelExpressDate.Value);
                //        storeCancelContract.StoreCancelEms = StoreCancelEms.Value;
                //        storeCancelContract.StoreCancelFinance = StoreCancelFinance.Checked;
                //        storeCancelContract.StoreCancelAffiliation = StoreCancelArchive.Value;
                //        storeCancelContract.StoreCancelNotSignReason = tb_StoreCancelNotSignReason.Text;
                //        storeCancelContract.StoreCancelRegionReceive = StoreCancelRegionReceive.Checked;
                //        storeCancelContract.CancelRemark = CancelRemark.Value;

                //        Storage.Save(Storage.Context3, storeCancelContract);
                //    }
             #endregion
        }

        #endregion


    }

}